import React, { useRef, useState } from 'react';
import { Button, message, Space, Popconfirm, Typography, Tag, Modal, Checkbox } from 'antd';
import { DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { getTransactionList, deleteTransaction } from '@/services/backend/transactionController';
import dayjs from 'dayjs';

const TransactionManage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [exportModalVisible, setExportModalVisible] = useState(false);
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);
  const actionRef = useRef<ActionType>();

  // 可导出的列配置
  const exportableColumns = [
    { key: 'tradeId', title: '交易编号' },
    { key: 'cardId', title: '卡号' },
    { key: 'tradeDate', title: '交易日期' },
    { key: 'tradeType', title: '交易类型' },
    { key: 'tradeMoney', title: '交易金额' },
    { key: 'remark', title: '备注' }
  ];

  // 删除交易记录
  const handleDelete = async (row: any) => {
    setLoading(true);
    try {
      const response = await deleteTransaction(row.tradeId);
      if (response.code === 1) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '删除失败');
      }
    } catch (error: any) {
      console.error('删除交易记录失败:', error);
      message.error(error?.data?.msg || '删除失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 显示导出配置弹窗
  const showExportModal = () => {
    setSelectedColumns(exportableColumns.map(col => col.key));
    setExportModalVisible(true);
  };

  // 处理列选择变化
  const handleColumnSelectChange = (checkedValues: string[]) => {
    setSelectedColumns(checkedValues);
  };

  // 导出交易记录为CSV
  const handleExport = async () => {
    if (selectedColumns.length === 0) {
      message.error('请至少选择一列进行导出');
      return;
    }

    try {
      // 获取全部数据用于导出（假设最多10万条）
      const response = await getTransactionList({
        page: 1,
        size: 100000,
      });
      const records = response.data?.records || response.data || [];
      if (records.length > 0) {
        // 生成CSV表头
        const selectedColumnConfigs = exportableColumns.filter(col => selectedColumns.includes(col.key));
        const header = selectedColumnConfigs.map(col => col.title).join(',') + '\n';

        // 生成CSV数据行
        const rows = records.map((item: any) => {
          return selectedColumns.map(key => {
            let value = item[key];
            if (key === 'tradeDate') {
              value = dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
            return value || '';
          }).join(',');
        });

        const csv = header + rows.join('\n');
        const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `交易记录_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.csv`;
        a.click();
        URL.revokeObjectURL(url);
        message.success('导出成功');
        setExportModalVisible(false);
      } else {
        message.warning('没有数据可导出');
      }
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请重试');
    }
  };

  const columns: ProColumns<any>[] = [
    {
      title: '交易编号',
      dataIndex: 'tradeId',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '卡号',
      dataIndex: 'cardId',
      valueType: 'text',
      search: true,
      render: (dom: any) => (
        <Typography.Text copyable>{dom}</Typography.Text>
      ),
    },
    {
      title: '交易日期',
      dataIndex: 'tradeDate',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '交易类型',
      dataIndex: 'tradeType',
      valueEnum: {
        '存入': { text: '存入', status: 'Success' },
        '支取': { text: '支取', status: 'Error' },
        '转账': { text: '转账', status: 'Processing' },
      },
      render: (_, record) => {
        let color = 'default';
        if (record.tradeType === '存入') color = 'green';
        if (record.tradeType === '支取') color = 'red';
        if (record.tradeType === '转账') color = 'blue';
        return <Tag color={color}>{record.tradeType}</Tag>;
      },
    },
    {
      title: '交易金额',
      dataIndex: 'tradeMoney',
      hideInSearch: true,
      render: (dom: any, record: any) => {
        const amount = typeof dom === 'number' ? dom : parseFloat(String(dom || '0'));
        if (isNaN(amount)) {
            console.error(`Invalid tradeMoney value:`, dom, `for record:`, record);
            return <Typography.Text type="danger">格式错误</Typography.Text>;
        }
        let symbol = '';
        let color: 'success' | 'danger' | undefined = undefined;
        if (record.tradeType === '存入') {
          symbol = '+';
          color = 'success';
        } else if (record.tradeType === '支取') {
          symbol = '-';
          color = 'danger';
        }
        return (
          <Typography.Text type={color}>
            {symbol}¥{amount.toFixed(2)}
          </Typography.Text>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
      render: (dom: any) => dom || '-',
    },
    {
      title: '交易时间区间',
      dataIndex: 'tradeDateRange',
      valueType: 'dateRange',
      hideInTable: true,
      search: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm 
            title="确定删除该交易记录？" 
            description="删除后无法恢复，请谨慎操作"
            onConfirm={() => handleDelete(record)}
          >
            <Typography.Link type="danger" disabled={loading}>
              <DeleteOutlined /> 删除
            </Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<any>
        headerTitle="交易管理"
        actionRef={actionRef}
        rowKey="tradeId"
        search={{ labelWidth: 120 }}
        toolBarRender={() => [
          <Button
            key="export"
            icon={<DownloadOutlined />}
            onClick={showExportModal}
          >
            导出CSV
          </Button>,
        ]}
        request={async (params) => {
          const { tradeDateRange, current, pageSize, ...rest } = params;
          let startDate, endDate;
          if (tradeDateRange && Array.isArray(tradeDateRange) && tradeDateRange.length === 2) {
            startDate = tradeDateRange[0];
            endDate = tradeDateRange[1];
          }
          const response = await getTransactionList({
            ...rest,
            page: current,
            size: pageSize,
            startDate,
            endDate,
          });
          console.log('Debug - TransactionManage response:', response);
          
          return {
            success: response.code === 1,
            data: response.data?.records || [],
            total: response.data?.total || 0,
          };
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
        }}
        options={{
          reload: true,
          density: true,
          setting: true,
        }}
      />

      <Modal
        title="选择导出列"
        open={exportModalVisible}
        onOk={handleExport}
        onCancel={() => setExportModalVisible(false)}
        width={400}
      >
        <Checkbox.Group
          options={exportableColumns.map(col => ({ label: col.title, value: col.key }))}
          value={selectedColumns}
          onChange={handleColumnSelectChange as any}
        />
      </Modal>
    </PageContainer>
  );
};

export default TransactionManage; 